package script

import (
	"bufio"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"io"
	"os/exec"
	"runtime"
	"sync"
)

// Command 这里为了简化，我省去了stderr和其他信息
// 目前只支持在linux上执行命令
func Command(cmd string) error {
	// c = exec.Command("cmd","/C", cmd)
	c := exec.Command("/bin/bash", "-c", cmd)

	stdout, err := c.StdoutPipe()
	if err != nil {
		return err
	}
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		reader := bufio.NewReader(stdout)
		for {
			readString, err := reader.ReadString('\n')
			if err != nil || err == io.EOF {
				return
			}
			byte2String := ConvertByte2String([]byte(readString), "GB18030")
			fmt.Print(byte2String)
		}
	}()
	err = c.Start()
	wg.Wait()
	return err
}

// commandNoStout 这里为了简化，我省去了stderr和其他信息
// 目前只支持在linux上执行命令, 没有输出
func commandNoStout(cmd string) error {
	c := exec.Command("/bin/bash", "-c", cmd)
	err := c.Run()
	if err != nil {
		return err
	}
	return err
}

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func ConvertByte2String(byte []byte, charset Charset) string {
	var str string
	switch charset {
	case GB18030:
		var decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}
	return str
}

// 执行命令
func ExecCmd(cmd string) error {
	sysType := runtime.GOOS
	if sysType == "windows" {
		// windows系统
		return nil
	}
	err := Command(cmd)
	if err != nil {
		return err
	}
	return err
}

// 执行命令
func ExecCmdNoStout(cmd string) error {
	sysType := runtime.GOOS
	if sysType == "windows" {
		// windows系统
		return nil
	}
	err := commandNoStout(cmd)
	if err != nil {
		return err
	}
	return err
}
